package com.gc.server.controller.api;

import com.gc.server.entity.*;
import com.gc.server.enums.AccountTypeEnum;
import com.gc.server.enums.LevelEnum;
import com.gc.server.enums.UserStatusEnum;
import com.gc.server.service.*;
import com.gc.server.vo.UserVo;
import com.github.pagehelper.PageHelper;
import com.yf.annotation.IgnoreAuth;
import com.yf.annotation.LoginUserId;
import com.yf.entity.TokenEntity;
import com.yf.entity.WxUser;
import com.yf.response.R;
import com.yf.response.RRException;
import com.yf.service.TokenService;
import com.yf.service.WxAppService;
import com.yf.service.WxPayService;
import com.yf.service.WxWebService;
import com.yf.tz.entity.AccountEntity;
import com.yf.tz.service.AccountRecordService;
import com.yf.tz.service.AccountService;
import com.yf.tz.vo.AccountRecordVo;
import org.aspectj.apache.bcel.generic.IINC;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/user")
public class ApiUserController {

    @Autowired
    private UserService userService;

    @Autowired
    private WxWebService wxWebService;

    @Autowired
    private TokenService tokenService;

    @PostMapping("/test/login")
    @IgnoreAuth
    public R testLogin(Long userId, Long pid) {
        UserEntity userEntity = userService.get(userId);
        if (userEntity == null) {
            if (pid == null) {
                throw new RRException("请扫推荐人的二维码完成注册!");
            }
            // 模拟微信获取基本信息
            userEntity = new UserEntity();
            userEntity.setAvatar("https://dss3.baidu.com/-rVXeDTa2gU2pMbgoY3K/it/u=1189779147,4248115718&fm=202&mola=new&crop=v1");
            userEntity.setName("asdad");
            userEntity.setOpenId("1121asdad");
            return R.ok(userEntity);
        }
        if (userEntity.getStatus().equals(UserStatusEnum.BAN.getIndex())) {
            return R.ok(userEntity);
        } else {
            TokenEntity tokenEntity = tokenService.createToken(userId);
            return R.ok(userEntity).putExtra("token", tokenEntity.getToken());
        }
    }

    @Autowired
    private WxAppService wxAppService;


    /**
     * 小程序登录
     *
     * @return
     */
    @PostMapping("/login")
    @IgnoreAuth
    public R login(String code) {
        WxUser wxUser = wxAppService.getBaseWxUser(code);
        String wxId = wxUser.getOpenId();
        if (wxUser.getUnionId() != null && !wxUser.getUnionId().equals("")) {
            wxId = wxUser.getUnionId();
        }
        UserEntity userEntity = userService.findByWxId(wxId);
        if (userEntity != null) {
//            if(userEntity.getOpenId()==null){
                userEntity.setOpenId(wxUser.getOpenId());
                userEntity.setUnionId(wxUser.getUnionId());
                userEntity.setAvatar(wxUser.getHeadImgUrl());
                userService.update(userEntity);
//            }
            TokenEntity tokenEntity = tokenService.createToken(userEntity.getId());
            return R.ok(tokenEntity.getToken()).putExtra("user", userEntity);
        }
        return R.ok().putExtra("wxUser", wxUser);
    }


    /**
     * 小程序
     * 点击卡片注册
     * 或者扫码注册
     *
     * @param encryptedData
     * @param iv
     * @param pid
     * @param unionId
     * @param openId
     * @param avatar
     * @param name
     * @return
     */
    @PostMapping("/register")
    @IgnoreAuth
    public R register(Long topUserId, String unionId, String openId, String avatar, String name) {
//        UserEntity userEntity = userService.register(topUserId, unionId, openId, avatar, name);
//        TokenEntity tokenEntity = tokenService.createToken(userEntity.getId());
//        return R.ok(tokenEntity.getToken()).putExtra("user", userEntity);
        throw new RRException("请先注册!");
    }


    @Autowired
    private LevelService levelService;

    @Autowired
    private AccountService accountService;

    /**
     * 小程序获取用户信息
     *
     * @param userId
     * @return
     */
    @GetMapping("/info")
    public R userInfo(@LoginUserId Long userId) {
        UserEntity userEntity = userService.get(userId);
        //级别信息
        LevelEntity level = levelService.get(userEntity.getLevelId());
        //账户信息
        List<AccountEntity> accountEntities = accountService.findByUserId(userId);
        return R.ok(userEntity).putExtra("level", level).putExtra("accounts", accountEntities);
    }

    @Autowired
    private ShopService shopService;

    @Autowired
    private SchoolService schoolService;


    @Autowired
    private AccountRecordService recordService;

    @GetMapping("/record")
    public R record(@LoginUserId Long userId, Integer type, String date) {
        PageHelper.orderBy("record.id desc");
        List<AccountRecordVo> vos = recordService.findByUserIdAndType(userId, type, date);
        return R.ok(vos);
    }

    @PostMapping("/recharge")
    public R recharge(@LoginUserId Long userId, BigDecimal amount) {
        String res = accountService.recharge(userId, amount);
        return R.ok(res);
    }

    @Autowired
    private WxPayService wxPayService;

    @RequestMapping("/recharge/pay")
    @IgnoreAuth
    public String payRecharge(@RequestBody String body) {
        Map<String, String> map = wxPayService.handleWxNotice(body);
        String orderNo = map.get("out_trade_no");
        BigDecimal totalPay = new BigDecimal(map.get("total_fee"));
        accountService.rechargePay(orderNo, totalPay);
        return "<xml>\n" +
                "  <return_code><![CDATA[SUCCESS]]></return_code>\n" +
                "  <return_msg><![CDATA[OK]]></return_msg>\n" +
                "</xml>";
    }



    /**
     * 微信H5登录
     *
     * @param code
     * @param pid
     * @param levelId
     * @return
     */
    @PostMapping("/wx/login")
    @IgnoreAuth
    public R wxLogin(String code, Long pid) {
        WxUser wxUser = wxWebService.getWxUser(code);
        String wxId  = wxUser.getUnionId();
        if(wxId==null||wxId.equals("")){
            wxId = wxUser.getOpenId();
        }
        UserEntity userEntity = userService.findByWxId(wxId);
        // 没有登录就注册
        if (userEntity == null) {
            if (pid == null) {
                throw new RRException("请扫推荐人的二维码完成注册!");
            }
            userEntity = new UserEntity(wxUser.getNickName(), wxUser.getHeadImgUrl(), wxUser.getOpenId(),wxUser.getUnionId(),pid);
//            UserEntity top = userService.get(pid);
            // 药店分享的直接保存
//            if(top.getLevelId()==null&&top.getLevelId().equals(LevelEnum.SHOP.getIndex())){
//                // 药店介绍的直接注册为游客 并且激活 前端禁止访问
//                userEntity.setStatus(UserStatusEnum.ACTIVE.getIndex());
//                userEntity.setLevelId(Long.valueOf(LevelEnum.CUSTOM.getIndex()));
//                // 登录成功 生成token
//                TokenEntity tokenEntity = tokenService.createToken(userEntity.getId());
//                userService.save(userEntity);
//                return R.ok(userEntity).putExtra("token",tokenEntity.getToken());
//            }
            return R.ok(userEntity);
        }
        if(userEntity.getOpenId()==null){
            userEntity.setOpenId(wxUser.getOpenId());
            userService.update(userEntity);
        }
        // 注册了没有激活
        if (userEntity.getStatus() == null || userEntity.getStatus().equals(UserStatusEnum.BAN.getIndex())) {
            return R.ok(userEntity);
        } else {
            // 登录成功 生成token
            TokenEntity tokenEntity = tokenService.createToken(userEntity.getId());
            return R.ok(userEntity).putExtra("token", tokenEntity.getToken());
        }
    }

    /**
     * 业务员药店注册
     *
     * @param userEntity
     * @return
     */
    @PostMapping("/h5/register")
    @IgnoreAuth
    public R busRegister(UserEntity userEntity) {
        if(userEntity.getId()!=null){
            userService.update(userEntity);
            //更新总部信息
            if(userEntity.getShopId()!=null){
                ShopEntity shop = shopService.get(userEntity.getShopId());
                LinkHeadEntity head = headService.get(shop.getHead());
                if(head!=null){
                    userEntity.setLinkName(head.getName());
                }
            }
        }else {
            userEntity = userService.register(userEntity);
        }
        return R.ok(userEntity);
    }

    @Autowired
    private LinkHeadService headService;

    /**
     * 根据ID获取名字
     *
     * @param id
     * @return
     */
    @GetMapping("/name/{id}")
    @IgnoreAuth
    public R baseUserInfo(@PathVariable Long id) {
        UserEntity userEntity = userService.get(id);
        if (userEntity.getStatus().equals(UserStatusEnum.BAN.getIndex())) {
            return R.ok();
        }
        return R.ok(userEntity.getName());
    }

    /**
     * 获取下面某个级别的所有人 激活的
     *
     * @param userId
     * @param id
     * @return
     */
    @GetMapping("/lv/{id}")
    public R listByTop(@LoginUserId Long userId, @PathVariable Long id,Integer  status) {
        List<UserEntity> userEntities = userService.findMyShopUserAndLv(userId, id);
        if(status!=null){
            userEntities = userEntities.stream().filter(userEntity -> userEntity.getStatus().equals(status)).collect(Collectors.toList());
        }
        return R.ok(userEntities);
    }

    /**
     * 找出某人下面用户
     * @param userId
     * @return
     */
    @GetMapping("/list")
    public R listByTop(@LoginUserId Long userId){
        List<UserEntity> userEntities = userService.findMyShopUser(userId);
        return R.ok(userEntities);
    }

    //激活用户
    @PostMapping("/act/{id}")
    public R act(@LoginUserId Long userId,@PathVariable Long id){
        UserEntity user =   userService.act(userId,id);
        return R.ok(user);
    }


    /**
     * 获取某人的信息
     * @param userId
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R info(@PathVariable Long id){
        UserEntity userEntity = userService.get(id);
        //相关统计 我的积分 我的店员 我的门店  我的学校
        //积分
        Integer sumUser = 0;
        Integer sumShop = 0;
        Integer sumSchool = 0;
        //账户信息
        AccountEntity point = accountService.findByUserIdAndType(id,AccountTypeEnum.POINT.getIndex());
//        for (AccountEntity accountEntity : accountEntities){
//            if(accountEntity.getType().equals(AccountTypeEnum.POINT.getIndex())){
//                point = accountEntity.getAmount();
//            }
//        }
        //店员
        List<UserEntity> userEntities = userService.findMyShopUser(id);
        sumUser = userEntities.size();
        //门店
        List<ShopEntity> shopEntities = shopService.findByUserId(id);
        sumShop = shopEntities.size();
        //学校
        List<SchoolEntity> schoolEntities = schoolService.findByUserId(id);
        sumSchool = schoolEntities.size();
        return R.ok(userEntity).putExtra("point",point.getAmount()).putExtra("sumUser",sumUser).putExtra("sumShop",sumShop).putExtra("sumSchool",sumSchool);
    }

    @GetMapping("/top")
    public R findMyShopUser(@LoginUserId Long userId) {
        List<UserEntity> list = userService.findMyShopUser(userId);
        return R.ok(list);
    }


    @GetMapping("/sum")
    public R sumUser(@LoginUserId Long userId, Date startDate,Date endDate,Long uid){
        List<UserEntity> list = userService.sumByTop(userId,startDate,endDate,uid);
        return R.ok(list);
    }



    /**
     * 找到业务员以及业务员以上的用户
     * @param userId
     * @return
     */
    @GetMapping("/top/lv/gt/bus")
    public R findMyShopUserAndLV(@LoginUserId Long userId) {
        List<UserEntity> list = userService.findChildren(userId);
        Map<String,List<UserEntity>> map = new HashMap();
        list.forEach(l->{
            LevelEntity level = levelService.findByUserId(l.getId());
            if(level==null)return;
            if(level.getLv()>=LevelEnum.BUS.getIndex()){
                List<UserEntity> tem = new ArrayList<>();
                if(map.containsKey(level.getName())){
                    tem = map.get(level.getName());
                }
                tem.add(l);
                map.put(level.getName(),tem);
            }
        });
        return R.ok(map);
    }


//    /**
//     * 找出跟某人相关的药店
//     * @param userId
//     * @return
//     */
//    @GetMapping("/shop")
//    public R shop(@LoginUserId Long userId){
//        UserEntity userEntity = userService.get(userId);
//        List<ShopEntity> list = shopService.findByName(userEntity.getName());
//        return R.ok(list);
//    }


}
